package com.fxb.learn.fxb_aop.apo;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author fangjiaxiaobai
 * @date 2020-09-17 11:00
 * @since 1.0.0
 */
@Component
@Aspect
public class PointCutDemo {

    @Pointcut("@annotation(com.fxb.learn.fxb_aop.annotion.C4S)")
    public void CharacterToStringCut() {

    }

    @Before("CharacterToStringCut()")
    public void CharacterToStringAround(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException, InstantiationException {
        String methodName = joinPoint.getSignature().getName();
        // 判断参数数量
        Object[] args = joinPoint.getArgs();
        Class<Object>[] parameterTypes = new Class[args.length];
        if (args.length > 0) {
            List<? extends Class<?>> collect = Stream.of(args).map(arg -> arg.getClass())
                    .collect(Collectors.toList());
            Class<Object>[] a = new Class[]{};
            parameterTypes = collect.toArray(a);
        }
        String name = joinPoint.getTarget().getClass().getName();
        Object instance = Class.forName(name).newInstance();
        Method method = joinPoint.getTarget().getClass().getMethod(methodName, parameterTypes);
        // 解析参数值数量, 默认使用String
        String[] strings = Stream.of(parameterTypes).map(Class::getName).collect(Collectors.toList()).toArray(new String[]{});
        method.invoke(instance, strings);
    }

}
